﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Caching;
using System.Security.Principal;
using System.Linq;
using MyDMS.DAL;

public partial class Login : Page
{
    private const string RootPath = "/MyDMS";
    private MyDMSEntity _myDmsEntity=new MyDMSEntity();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Office> lstOffice = _myDmsEntity.Office.ToList();
            if (lstOffice.Count == 0)
            {
                pnlRegister.Visible = true;
            }
        }
    }

    protected void lgnUser_Authenticate(object sender, AuthenticateEventArgs e)
    {
        // If valid admin or user
        if (PageBaseClass.AuthenticateAdmin(lgnUser.UserName, lgnUser.Password) || PageBaseClass.AuthenticateUser(lgnUser.UserName, lgnUser.Password))
        {
            Session["Author"] = PageBaseClass.Author;
            string redirectUrl = FormsAuthentication.GetRedirectUrl(lgnUser.UserName, lgnUser.RememberMeSet);
            string[] roles;
            if (PageBaseClass.Author.is_Administrator)
            {
                roles = new string[] { "Admin", "Member" };
            }
            else
            {
                roles = new string[] { "Member" };
                // If user is valid and trying to access admin pages
                if (redirectUrl.StartsWith(RootPath + "/admin", StringComparison.OrdinalIgnoreCase))
                {
                    redirectUrl = RootPath + "/Default.aspx";
                }
            }

            FormsAuthentication.SetAuthCookie(lgnUser.UserName, lgnUser.RememberMeSet);
            Cache.Add(PageBaseClass.Author.user_Name, roles, null, DateTime.MaxValue, TimeSpan.FromHours(1), CacheItemPriority.BelowNormal, null);
            Response.Redirect(redirectUrl);
        }
    }
}
